package org.danger.t7.common.redis;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisTemplateAutoConfiguration {

//    @Bean
//    public JsonRedissonAutoConfigurationCustomizer jsonRedissonAutoConfigurationCustomizer(){
//        return new JsonRedissonAutoConfigurationCustomizer();
//    }

    /**
     * 模板定义
     *
     * @param redisConnectionFactory redisConnectionFactory
     * @return org.springframework.data.redis.core.RedisTemplate<java.lang.String
     */
    @Bean
    public JdkRedisTemplate jdkRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        return new JdkRedisTemplate(redisConnectionFactory);
    }


    /**
     * @param redisConnectionFactory redisConnectionFactory
     * @return JsonRedisTemplate
     */
    @Primary
    @Bean
    public JsonRedisTemplate jsonRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        return new JsonRedisTemplate(redisConnectionFactory);
    }


    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        return new StringRedisTemplate(redisConnectionFactory);
    }


    /**
     * replace empty password with null in redis properties
     * @return bean post processor
     */
    @Bean
    public BeanPostProcessor redisPropertiesPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof RedisProperties) {
                    RedisProperties redisProperties = (RedisProperties) bean;
                    if (!StringUtils.hasText(redisProperties.getPassword())) {
                        redisProperties.setPassword(null);
                    }
                }
                return bean;
            }
        };
    }


}
